import actionType from "./index";
import UserService from "../model/user/Service"; //用户的接口

let Login = (playload: any) => {
  return {
    type: actionType.LOGIN,
    playload,
  };
};

let asyncLogin = (playload: any) => {
  return async (dispatch: any) => {
    return new Promise(async (resolve, reject) => {
      //先查询
      let { data } = await UserService.login(playload);
      if (data.code == 1) {
        window.localStorage.setItem("token", data.token);
        resolve({
          msg: "登陆成功",
          data,
        });
        dispatch(Login(data));
      } else {
        reject({ msg: "登陆失败", data });
      }
    });
  };
};

let asyncToken = (playload: any) => {
  return async (dispatch: any) => {
    return new Promise(async (resolve, reject) => {
      let { data } = await UserService.querytoken(playload);
      if (data) {
        resolve({
          msg: "登陆成功",
          data,
        });
      } else {
        reject({ msg: "登陆失败", data });
      }
    });
  };
};

let asyncAdduser = (playload: any) => {
  return async (dispatch: any) => {
    return new Promise(async (resolve, reject) => {
      let { data } = await UserService.adduser(playload);
      if (data.code == 1) {
        resolve({
          msg: "添加成功",
          data,
        });
      } else {
        reject({ msg: "添加失败", data });
      }
    });
  };
};

let asyncGetuserinfos = (playload: any) => {
  return async (dispatch: any) => {
    return new Promise(async (resolve, reject) => {
      let { data } = await UserService.getuserinfos(playload);
      if (data.code == 1) {
        resolve({
          msg: "成功",
          data,
        });
      } else {
        reject({ msg: "失败", data });
      }
    });
  };
};

export { Login, asyncLogin, asyncToken, asyncAdduser, asyncGetuserinfos };
